<template>
  <div class="survey" v-loading="loading">
    <div class="top">
      <div class="search">
        <div class="contition">
          <div class="wrap_time">
            <date-time @changeType = "changeType" type="other_half_hour" :query="query" @isFold="isShowFold" :isTimePeriod = "true"></date-time>
            <el-button type="primary" class="primary_btn fr find" @click.stop='search'>{{$t('public.search2')}}</el-button>
            <div class="clear"></div></div>
          <div class="wrap_drop">
            <unfold :isShow="isFold" :title="[]">
              <template slot="unfoldSlot">
                <div class="skill">
                  <span class="ski">{{$t('call.callType')}} : </span>
                  <el-select size="mini"
                             v-model.trim="value"
                             :placeholder="$t('webchat.webchatAll')">
                    <el-option
                      v-for="item in options"
                      :label="item.label"
                      :value="item.value"
                      :key="item.value">
                    </el-option>
                  </el-select>
                </div>
                <div class="agent_search">
                  <div class="skill">
                    <el-radio-group v-model="radio1"
                                  size = "mini"
                                  @change = "changeAgentBig">
                      <el-radio :label="1">{{$t('report.lookAgentWork')}}</el-radio>
                      <el-radio :label="0">{{$t('report.lookSkillWork')}}</el-radio>
                      <span class="tip">
                        <el-tooltip
                          transition="fade-leave"
                          effect="dark"
                          :content="$t('report.queueChangeAgentTip')"
                          placement="bottom">
                          <i class="icon iconfont icon-tixingweizhi"></i>
                        </el-tooltip>
                      </span>
                    </el-radio-group></div>
                  <div class="wrap_conti" v-show="radio1">
                    <span class="chan_ag">{{$t('report.chooseAgent')}}:</span>
                    <el-radio-group v-model="radio3"
                                  size = "mini"
                                  @change = "changeAgent">
                      <div>
                        <el-radio :label="1">{{$t('public.checkAll')}}</el-radio></div>
                      <div class="skill">
                        <el-radio :label="2">{{$t('report.accordAgentChoose')}}</el-radio>
                        <!-- <el-select v-model="query.selectedAgentList"
                                     multiple
                                     filterable
                                     :disabled = "radio3 !== 2"
                                     size="mini"
                                     @change="agentsChange"
                                     :placeholder="$t('report.pleChoseAgent')">
                            <el-option
                              v-for="item in agents"
                              :label="item.label"
                              :value="item.value"
                              :key="item.value">
                            </el-option>
                          </el-select> -->
                        <m7Select class="el-select" :disabled = "radio3 !== 2" filterable multiple :options="selectAgents" v-model="query.selectedAgentList"></m7Select>
                        <el-checkbox :disabled = "radio3 !== 2"
                                     v-model.trim="query.includeSubordinate">
                          {{$t('public.includeSubordinate')}}</el-checkbox></div>
                      <div class="skill">
                        <el-radio :label="3">{{$t('report.chooseSkillAgent')}}</el-radio>
                        <el-select size="mini"
                                   v-model.trim="currentQueue"
                                   :placeholder="$t('report.queueNaSea')"
                                   multiple
                                   :disabled = "radio3 !== 3"
                                   filterable
                                   @change = "change">
                          <el-option v-for="item in queues"
                                     :label="item.DisplayName"
                                     :value="item._id"
                                     :key="item._id"></el-option>
                        </el-select>
                        <el-checkbox :disabled = "radio3 !== 3"
                                       v-model.trim="isShowAgent">
                            {{$t('report.isShowSkillAgent')}}</el-checkbox></div>
                      <div class="skill dept">
                        <el-radio :label="4">{{$t('report.accordDeptChoose')}} </el-radio>
                        <el-select size="mini"
                                   v-model.trim="currentdept"
                                   :placeholder="$t('report.deptNaSea')"
                                   multiple
                                   :disabled = "radio3 !== 4"
                                   filterable
                                   @change = "changeDept">
                          <el-option v-for="item in depts"
                                     :label="item.name"
                                     :value="item.treePath"
                                     :key="item._id"></el-option>
                        </el-select>
                        <el-checkbox :disabled = "radio3 !== 4"
                                     v-model.trim="isShowDeptAgent"
                                     @change = changeShowDept>
                            {{$t('report.isShowDeptAgent')}}</el-checkbox></div>
                    </el-radio-group>
                  </div>
                  <div class="wrap_conti" v-show="!radio1">
                    <div class="skill">
                      <span class="ski">{{$t('report.chooseSkill')}}:</span>
                      <el-select size="mini"
                                 v-model.trim="currentQueueS"
                                 :placeholder="$t('report.queueNaSea')"
                                 filterable
                                 multiple
                                 @change = "changeSkill">
                        <el-option v-for="item in queues"
                                   :label="item.DisplayName"
                                   :value="item.Exten"
                                   :key="item._id"></el-option>
                      </el-select>
                    </div>
                  </div>
                </div>
              </template>
            </unfold>
          </div>
        </div>
      </div>
      <affix :label="$t('report.callReportApproveSurvey')"></affix>
    </div>
    <div v-show="!isShowDetail" class="tab" :id = "id">
      <div class="export">
        <el-button class="primary_btn fr formal" v-if="configFormula" @click="$refs.formulaEditorDialog.open()">{{$t('report.formalTitle')}}</el-button>
        <!-- <el-button class="primary_btn fr report_excel_btn"
          v-if="$store.getters.exportFromEnd"
          v-on:click="exportExcel"
        >{{$t('report.exportXls')+($store.state.xlsxExportMode==='Both'?'(旧)':'')}}</el-button> -->

        <el-button class="primary_btn fr report_excel_btn"
          v-on:click="exportXlsx"
        >{{$t('report.exportXls')}}</el-button>
        <el-button class="primary_btn fr pdf" v-on:click="exportPdf">{{$t('report.exportPDF')}}</el-button>
        <el-button class="primary_btn fr pdf" v-on:click="showDetail">{{$t('call.queryDetail')}}</el-button>
        <el-tooltip class="item" :content="$t('report.surveyDetailText')" effect="dark" placement="bottom">
          <el-button class="primary_btn fr pdf" v-show="isShowDetailExport" v-on:click.stop="exportExcel(true)">{{$t('report.exportDetailXls')}}
            <span class="tip"><i class="iconfont icon-tixingweizhi"></i></span>
          </el-button>
        </el-tooltip>
      </div>
      <div class="deploy">
        <el-collapse accordion>
          <el-collapse-item>
            <template slot="title">
              <span class="fl explain">{{$t('report.toggleInstructe')}}</span>
            </template>
            <div>
              {{$t('report.callOutConnectAllNum')}}<br>
              {{$t('report.callPartakeRate')}}<br>
              {{$t('report.callPartakeEvalateNum')}}<br>
              {{$t('report.callInConnectAllNum')}}<br>
              {{$t('report.callCRs')}}<br>
              6.{{$t('report.NormalTransferAcceptCount')}}<br>
              7.{{$t('report.DialTransferAcceptCount')}}<br>
              8.{{$t('report.RollOutAnswerCount')}}
              <div v-show="isInviteStatistics">
                9.{{$t('report.callUserInviteCount')}}<br>
                10.{{$t('report.callInviteCount')}}
              </div>
              <p class="custom_alg">{{$t('report.ziDingYi')}}：</p>
              <p v-for="(item, index) in formulas" :key="item.name">
                {{index + indexStart}}.{{item.formulaInstr}}
              </p>
            </div>
          </el-collapse-item>
        </el-collapse>
      </div>
      <report-table :data="serveNumData" :sum="sum" :config="[...headOptions.Config, ...formulasConfig]"> </report-table>
    </div>
    <suevey-detail :formulas="formulas" @exportPdf="exportPdf" @exportExcel="exportExcel" @close="returnCur" @exportXlsx="exportXlsx" v-show="isShowDetail" :data="detailServeNumData" :customHeader="formulasConfig" :sum="sum" :config="headOptions.Config"></suevey-detail>
    <el-dialog :close-on-click-modal="false" modal-append-to-body lock-scroll top="10%" :title="$t('report.reportExportHelp')" :visible.sync="dialogVisible" width="30%">
      <span>{{$t('report.reportExportTipTitle')}}</span>
      <span slot="footer" class="dialog-footer">
        <el-button class="primary_btn" @click="dialogVisible = false">{{$t('public.cancel')}}</el-button>
        <el-button class="primary_btn" type="primary" @click="confirm">{{$t('public.confirm')}}</el-button>
      </span>
    </el-dialog>
    <!-- 自定义公式组件 -->
    <FormulaEditorDialog ref="formulaEditorDialog" :headOptionsConfig="headOptions.Config" @closeFormulaDialog="closeFormulaDialog" :reportType="id"/>
  </div>
</template>
<script>
  import affix from '../../../ui-modules/affix/Affix.vue'
  import unfold from '../../../ui-modules/unfold/index.vue'
  import dateTime from '../base/dateDrill.vue'
  import sueveyDetail from './CallReportApproveSurveyDetail.vue'
  import {exportReportPdf, checkTime, searchTime, sortDataByKey, mixData, headOptionsToXlsxHeaders} from '@/utils/reportUtils.js'
  import {deepClone, optionTimeTypeCheck, getDateTime, isHasFunc } from '@/utils/m7Utils.js'
  import reportTable from '../base/crsTable.vue'
  import * as XlsxUtil from 'src/utils/XlsxUtil.umd.js'
  import FormulaEditorDialog from '../base/FormulaEditorDialog.vue'
  // import { parseFormulaStr, dal2Rpn, STATUS, evalRpn, toNumber } from '../base/formulaUtil.js'
  export default {
    name: 'survey',
    data () {
      return {
        configFormula: true, // 自定义公式的权限
        dateType: 'day',
        isInviteStatistics: false, // pbx是否升级标识
        detailServeNumData: [],
        formulas: [], // 公式数据
        // wrapAgents: false, // 是防止座席数据量展示太大设置样式index -1
        isShowAgent: false, // 是否展示技能组下的座席
        isShowDeptAgent: false, // 是否展示部门下的座席
        isShowDetail: false, // 是否展示满意度评价详情
        isFold: false, // 是否展示搜索条件
        currentQueueS: [], // 技能组号
        radio3: 1, // 各座席工作量下面选择切换绑定得值
        radio1: 1, // 各座席工作量和各技能组切换绑定值
        depts: [], // 部门渲染下拉数据
        currentdept: [], // 选择部门绑定得id值
        loading: false,
        selectedAgentListClone: [], // 是否展示座席得复制版
        id: 'call_report_approve_survey', // 查询id
        query: {
          selectedAgentList: [],
          includeSubordinate: false
        },
        currentQueue: [], // 各座席量技能组绑定值
        agents: [], // 渲染座席数据
        queues: [], // 渲染技能组数据
        value: '', // 呼叫类型绑定值
        dialogVisible: false, // 导出pdf弹窗开关值
        options: [ // 呼叫类型渲染数据
          {label: this.$t('qualityCheck.normalCallIn'), value: 'normal'},
          {label: this.$t('qualityCheck.callOut'), value: 'dialout'},
          {label: this.$t('qualityCheck.callInTrans'), value: 'transfer'},
          {label: this.$t('qualityCheck.callOutTrans'), value: 'dialTransfer'},
          {label: this.$t('webchat.webchatAll'), value: ''}
        ],
        sum: [], // 合计变量
        headOptions: { // 表头数据
          Config: []
        },
        isSearch: false, // 查询时不触发监听自定义表头的变化
        baseData: [], // 请求获取的基础数据
        agentReportData: [], // 通话相关数据
        serveNumData: [] // 表格数据
      }
    },
    methods: {
      // 子组件切换时间类型传上来得方法 触发计算属性
      changeType (type) {
        this.dateType = type
      },
      returnCur () {
        this.isShowDetail = false
      },
      // 展示满意度详情页
      showDetail () {
        this.detailServeNumData = this.serveNumData
        this.isShowDetail = true
      },
      // 自定义公式弹窗关闭外抛事件
      closeFormulaDialog () {
        this.isSearch = false
        this.$store.dispatch('queryFetchFormula', {type: this.id}).then((resp) => {
          if (resp.success) {
            this.formulas = resp.data.Formulas
          }
        })
      },
      // 是否展开收起查询条件
      isShowFold (bool) {
        this.isFold = bool
      },
      // 是否展示部门下的座席
      changeShowDept (cur) {
        if (cur) {
          this.query.selectedAgentList = this.selectedAgentListClone
        } else {
          this.query.selectedAgentList = []
        }
      },
      // 各座席工作量和技能组切换, 初始化一些数据
      changeAgentBig (num) {
        delete this.query.queryExten
        this.currentQueueS = []
        this.query.selectedAgentList = []
        this.selectedAgentListClone = []
        this.currentdept = []
        this.currentQueue = []
        this.query.includeSubordinate = false
        this.isShowAgent = false
        this.isShowDeptAgent = false
      },
      // 切换技能组
      changeSkill (id) {
        this.query.queryExten = id.join(',')
      },
      // 各座席量选择切换
      changeAgent () {
        this.query.selectedAgentList = []
        this.selectedAgentListClone = []
        this.currentdept = []
        this.currentQueue = []
        this.isShowAgent = false
        this.isShowDeptAgent = false
        this.query.includeSubordinate = false
      },
      // 部门切换执行方法，筛选座席
      changeDept (deptTreePaths) {
        this.query.selectedAgentList = []
        this.selectedAgentListClone = []
        let deptIds = [] // 创建部门id数组集
        if (deptTreePaths.length !== 0) {
          for (let i = 0; i < deptTreePaths.length; i++) {
            if (deptTreePaths[i] === 'noDept') {
              deptIds.push('')
            } else {
              let deptIdArr = deptTreePaths[i].split('/')
              let deptId = deptIdArr[deptIdArr.length - 2] // 当前部门id
              deptIds.push(deptId) // 像部门数组中添加当前部门id
              for (let j = 0; j < this.depts.length; j++) {
                let isDeptIdArr = this.depts[j].treePath.split(deptId + '/')[1] // 判断当前部门下面得部门是否存在
                if (isDeptIdArr) {
                  // 切割部门id数组
                  deptIds = deptIds.concat(isDeptIdArr.split('/').filter(item => item))
                }
              }
            }
          }
          deptIds = Array.from(new Set(deptIds)) // 部门id去重
          let cloneAgentsArr = []
          cloneAgentsArr = this.agents.filter(item => { // 过滤座席信息得部门是否在部门数组里，是则返回
            return deptIds.includes(item.deptId)
          })
          cloneAgentsArr.map(item => {
            this.selectedAgentListClone.push(item.value)
          })
          if (this.isShowDeptAgent) {
            this.query.selectedAgentList = this.selectedAgentListClone
          }
        }
      },
      // 各座席量下的技能组切换筛选座席
      change (peerIds) {
        this.query.selectedAgentList = []
        this.selectedAgentListClone = []
        if (peerIds.length === 0) {
          return
        }
        let agentIds = []
        peerIds.map((id) => {
          this.queues.map((item) => {
            if (item._id === id) {
              agentIds = agentIds.concat(item.AssignMembers)
            }
          })
        })
        agentIds.map((obj) => {
          if (obj) {
            this.selectedAgentListClone.push(obj.agentID)
          }
        })
        if (this.isShowAgent) {
          this.selectedAgentListClone = Array.from(new Set(this.selectedAgentListClone))
          this.query.selectedAgentList = this.selectedAgentListClone
        } else {
          // 保存已选技能组下的座席信息 切换展示座席赋值
          this.selectedAgentListClone = Array.from(new Set(this.selectedAgentListClone))
        }
      },
      // 初始化查询条件
      getSearchQueryData (init) {
        let data = {reportType: 'call_report_approve_survey', account: this.$store.state.session.user.account}
        let userCondition = {type: this.$store.state.session.user.type, moduleUsers: this.$store.state.session.user.moduleUsers}
        data.user = userCondition
        let myQuery = deepClone(this.query)
        if (myQuery.timeType === 'other_half_hour') {
          let message = checkTime(myQuery.StartTime, myQuery.EndTime, false, false) // 校验类型与时间
          if (message !== true) {
            this.$message.error(this.$t(message))
            return
          }
        }
        if (init !== 'true') {
          let callType = this.value
          myQuery.callType = callType
          // 转换timeType查询条件
          myQuery.TimeType = myQuery.timeType
          delete myQuery.timeType
          myQuery.selectedAgentList = myQuery.selectedAgentList.join(',')
          myQuery.reportType = 'call_report_approve_survey'
          myQuery.account = this.$store.state.session.user.account
          myQuery.user = userCondition
          myQuery.AgentID = ''
          data = myQuery
          if (data.TimeType === 'other_half_hour') {
            delete data.yearReport
            delete data.monthReport
            delete data.dayReport
          }
          if (data.TimeType === 'year') {
            delete data.monthReport
            delete data.dayReport
          }
        } else {
          data = Object.assign(data, this.query)
        }
        if ((this.currentQueue.length !== 0 || this.currentdept.length !== 0) && this.selectedAgentListClone.length === 0) {
          myQuery.selectedAgentList = '000000'
        } else if (this.selectedAgentListClone.length !== 0) {
          myQuery.selectedAgentList = this.selectedAgentListClone.join(',')
        }
        return data
      },
      // 判断pbx是否升级处理下表头
      dealHeader (res) {
        let inviteNumArr = ['UserInviteCount', 'InviteCount']
        let config = res.tableHeader.Config.filter(item => {
          return !inviteNumArr.includes(item.name)
        })
        return config
      },
      // 查询数据的方法
      search (init) {
        var data = this.getSearchQueryData(init)
        if (!data) {
          return
        }

        this.loading = true
        this.$store.dispatch('queryCallApproveSurveyReport', data).then((res) => {
          if (this.$store.state.report.customExportData) {
            res = JSON.parse(this.$store.state.report.customExportData)
          }
          if (!res.success) {
            this.loading = false
            return
          }
          this.isSearch = true
          if (!this.isInviteStatistics) {
            res.tableHeader.Config = this.dealHeader(res)
          }
          this.headOptions = optionTimeTypeCheck(res.tableHeader)
          this.headOptions.Config = sortDataByKey(this.headOptions.Config, 'order')
          this.agentReportData = deepClone(res.agentReportData) // 返回座席工作量得数据
          let resData = res.data // 把返回座席里面得信息放到data
          this.$store.dispatch('queryFetchFormula', {type: this.id}).then((resp) => {
            if (resp.success) {
              this.formulas = resp.data.Formulas
              this.baseData = deepClone(resData) // 建立一个原始返回数据 避免处理数据时污染数据 配置自定义用到
              this.serveNumData = mixData(this.dealData(resData, this.agentReportData), this.formulas)
              if (this.isShowDetail) {
                this.detailServeNumData = this.serveNumData
              }
              this.sum = this.dealSum(resData, data, this.headOptions)
              this.loading = false
            } else {
              this.loading = false
            }
          })
        })
      },
      // 把返回得座席信息里面得值放到data
      // dealAllData (resData, agentReportData) {
      //   for (var k in resData) {
      //     let resFlag = resData[k]
      //     for (var m in agentReportData) {
      //       let flag = agentReportData[m]
      //       if (resFlag.AgentID === flag.AgentID) {
      //         resFlag.CallInAcceptCount = flag.CallInAcceptCount
      //         resFlag.CallOutAcceptCount = flag.CallOutAcceptCount
      //         resFlag.TransferAcceptCount = flag.TransferAcceptCount
      //         resFlag.DialTransferAcceptCount = flag.DialTransferAcceptCount
      //         resFlag.NormalTransferAcceptCount = flag.NormalTransferAcceptCount
      //         break;
      //       }
      //     }
      //   }
      //   return resData
      // },
      // 处理表格数据
      dealData (resData, isExport) {
        var data = this.getSearchQueryData()
        resData = deepClone(resData)
        var myQuery = data['query'] || deepClone(this.query)
        for (var i in resData) {
          let item = resData[i]
          item.approveSurveyRate = '0'
          // 判断通话类型显示参评率
          if (data.callType === 'normal') {
            item.approveSurveyRate = item.CallInAcceptCount > 0 ? Math.round((item.approveSurveyCount / item.CallInAcceptCount) * 100) : 0
          } else if (data.callType === 'dialout') {
            item.approveSurveyRate = item.CallOutAcceptCount > 0 ? Math.round((item.approveSurveyCount / item.CallOutAcceptCount) * 100) : 0
          } else if (data.callType === 'transfer') {
            item.approveSurveyRate = item.NormalTransferAcceptCount > 0 ? Math.round((item.approveSurveyCount / item.NormalTransferAcceptCount) * 100) : 0
          } else if (data.callType === 'dialTransfer') {
            item.approveSurveyRate = item.DialTransferAcceptCount > 0 ? Math.round((item.approveSurveyCount / item.DialTransferAcceptCount) * 100) : 0
          } else {
            let countNum = (item.CallOutAcceptCount || 0) + (item.CallInAcceptCount || 0) + (item.NormalTransferAcceptCount || 0) + (item.DialTransferAcceptCount || 0)
            if (countNum > 0 && item.approveSurveyCount > 0) {
              item.approveSurveyRate = Math.round((item.approveSurveyCount / countNum) * 100)
            }
          }
          item.approveSurveyRate += '%'
          for (var j in item) {
            if (j.substr(0, j.length - 1) === 'approveSurvey') {
              if (isExport === true) {
                if (item.approveSurveyCount) {
                  item[j + '_rate'] = Math.round(item[j] / item.approveSurveyCount * 100) + '%'
                } else {
                  item[j + '_rate'] = Math.round(item[j] / 1 * 100) + '%'
                }
              } else {
                if (item.approveSurveyCount) {
                  item[j] = item[j] + '(' + Math.round(item[j] / item.approveSurveyCount * 100) + '%' + ')'
                } else {
                  item[j] = item[j] + '(' + Math.round(item[j] / 1 * 100) + '%' + ')'
                }
              }
            }
          }
          let agent = this.$store.getters.agents[item.AgentID]
          item.agent_name = agent ? agent.displayName + '(' + agent.exten + ')' : ''
          item.agentName = agent ? agent.displayName + '(' + agent.exten + ')' : ''
          if (isExport === true) {
            item.agent_name = agent ? agent.displayName : ''
            item.agent_exten = agent ? agent.exten : ''
          }
        }
        resData = sortDataByKey(resData, 'agent_name', 'string')
        return resData
      },
      // 导出表格数据执行的方法(前端)
      exportXlsx (init) {
        var data = this.getSearchQueryData(init)
        if (!data) {
          return
        }

        this.loading = true
        this.$store.dispatch('queryCallApproveSurveyReport', data).then((res) => {
          if (this.$store.state.report.customExportData) {
            res = JSON.parse(this.$store.state.report.customExportData)
          }
          if (!res.success) {
            this.loading = false
            return
          }
          this.loading = false
          if (!this.isInviteStatistics) {
            res.tableHeader.Config = this.dealHeader(res)
          }
          var headOptions = optionTimeTypeCheck(res.tableHeader)
          headOptions.Config = sortDataByKey(headOptions.Config, 'order')

          let agentReportData = deepClone(res.agentReportData)
          let resData = res.data
          this.baseData = deepClone(resData) // 建立一个原始返回数据 避免处理数据时污染数据 配置自定义用到
          resData = this.dealData(resData, true)
          var sum = []
          resData = mixData(resData, this.formulas)
          if (resData.length !== 0) {
            sum = this.dealSum(resData, data, headOptions, true)
          }
          var tableData = resData.concat(sum)
          var Config = headOptions.Config
          var ConfigsTemp = []
          Config && Config.forEach(config => {
            if (!config.show) {
              return
            }
            ConfigsTemp.push(config)
            if (config.name === 'agent_name') {
              ConfigsTemp.push({
                show: config.show,
                displayname: '工号',
                name: 'agent_exten'
              })
            }
            if (config.name.substr(0, config.name.length - 1) === 'approveSurvey') {
              ConfigsTemp.push({
                show: config.show,
                displayname: config.displayname + '占比',
                name: config.name + '_rate'
              })
            }
          })
          if (init === 'Front') {
            Config = [...ConfigsTemp, ...this.formulasConfig]
            this.dealDetailExport(tableData, Config, ConfigsTemp.length)
            return
          }
          Config = [...ConfigsTemp, ...this.formulasConfig]

          var headers = headOptionsToXlsxHeaders(Config)

          var dh = XlsxUtil.getDownloadHelper(headers, tableData)
          var timeStamp = XlsxUtil.dateFormat(new Date(), 'yyyy-MM-dd hh-mm-ss')
          dh.download(this.$t('report.callReportApproveSurvey') + timeStamp)
        })
      },
      // 处理详情页得导出
      dealDetailExport (tableData, Config, Length) {
        let exportArr = []
        let row = 1
        let curCol = 0
        let isSetDetail = false // 判断是否有二级满意度
        for (let i = 0; i < Config.length; i++) {
          if (Config[i].sub && Config[i].sub.length) {
            isSetDetail = true
          }
        }
        let currentCol = 0
        let configLen = Length
        Config.forEach((item, index) => {
          let dataRow = isSetDetail ? 3 : 2 // 判断data从第几行开始
          currentCol++
          if (item.sub && item.sub.length) {
            // 合并添加至末尾
            exportArr.push({
              value: item.displayname,
              startRow: row,
              startCol: configLen + 1,
              endRow: row,
              merged: true,
              endCol: configLen + item.sub.length
            })
            // 正常循环
            exportArr.push({
              value: item.displayname,
              startRow: row,
              startCol: currentCol,
              endRow: row + 1,
              merged: true,
              endCol: currentCol
            })
            exportArr = exportArr.concat(this.renderTwoRow(item.sub, configLen, tableData))
            configLen = configLen + item.sub.length
          } else {
            if (isSetDetail) {
              if (item.name.indexOf('_formulas_') > -1) {
                exportArr.push({
                  value: item.displayname,
                  startRow: row,
                  startCol: configLen + 1 + curCol,
                  merged: true,
                  endRow: 2,
                  endCol: configLen + 1 + curCol
                })
                curCol++
              } else {
                exportArr.push({
                  value: item.displayname,
                  startRow: row,
                  startCol: currentCol,
                  merged: true,
                  endRow: 2,
                  endCol: currentCol
                })
              }
            } else {
              if (item.name.indexOf('_formulas_') > -1) {
                exportArr.push({
                  value: item.displayname,
                  startRow: row,
                  startCol: configLen + 1 + curCol,
                  merged: true,
                  endRow: row,
                  endCol: configLen + 1 + curCol
                })
                curCol++
              } else {
                exportArr.push({
                  value: item.displayname,
                  startRow: row,
                  startCol: currentCol,
                  endRow: row,
                  endCol: currentCol
                })
              }
            }
          }
          for (let k = 0; k < tableData.length; k++) {
            let curObj = tableData[k]
            if (item.name.indexOf('_formulas_') > -1) {
              exportArr.push({
                value: curObj[item.name],
                startRow: dataRow,
                startCol: configLen + curCol,
                endRow: dataRow,
                endCol: configLen + curCol
              })
            } else {
              exportArr.push({
                value: curObj[item.name],
                startRow: dataRow,
                startCol: currentCol,
                endRow: dataRow,
                endCol: currentCol
              })
            }
            dataRow++
          }
        })
        var dh = XlsxUtil.getDownloadRangesHelper(exportArr)
        var timeStamp = XlsxUtil.dateFormat(new Date(), 'yyyy-MM-dd hh-mm-ss')
        dh.download('座席满意度调查报表' + timeStamp)
      },
      // 处理二级满意度
      renderTwoRow (arr, cur, tableData) {
        let subArr = []
        arr.forEach((item, i) => {
          let dataRow = 3
          subArr.push({
            value: item.displayname,
            startRow: 2, // 开始行
            startCol: cur + i + 1, // 开始列
            endRow: 2, // 结束行
            endCol: cur + i + 1 // 结束列
          })
          for (let k = 0; k < tableData.length; k++) {
            let curObj = tableData[k]
            subArr.push({
              value: curObj[item.name],
              startRow: dataRow,
              startCol: cur + i + 1,
              endRow: dataRow,
              endCol: cur + i + 1
            })
            dataRow++
          }
        })
        return subArr
      },
      // 计算合计 data: 查询条件数据
      dealSum (resData, data, headOptions, isExport) {
        var sum = [{agent_name: this.$t('report.total')}]
        resData = deepClone(resData)
        // let headConfig = headOptions.Config
        // 判断不显示某个字段
        // for (var f in headConfig) {
        //   if (data.callType === 'normal') {
        //     if (headConfig[f].name === 'approveSurveyOutRate' || headConfig[f].name === 'CallOutAcceptCount') {
        //       headOptions.Config[f].show = false
        //     }
        //   } else if (data.callType === 'dialout') {
        //     if (headConfig[f].name === 'approveSurveyInRate' || headConfig[f].name === 'CallInAcceptCount') {
        //       headOptions.Config[f].show = false
        //     }
        //   } else if (data === 'call_report_approve_survey' || headConfig[f].name === '') {
        //     if (headConfig[f].name === 'approveSurveyInRate' || headConfig[f].name === 'approveSurveyOutRate') {
        //       headOptions.Config[f].show = false
        //     }
        //   }
        // }
        for (var i in resData) {
          let item = resData[i]
          for (var j in item) {
            if (sum[0][j] === undefined) {
              sum[0][j] = 0
            }
            if (j !== 'agent_name') {
              sum[0][j] += item[j]
            }
          }
        }
        // 合计得判断参与率得计算
        sum[0].approveSurveyRate = '0'
        if (data.callType === 'normal') {
          sum[0].approveSurveyRate = sum[0].CallInAcceptCount ? Math.round((sum[0].approveSurveyCount / sum[0].CallInAcceptCount) * 100) : 0
        } else if (data.callType === 'dialout') {
          sum[0].approveSurveyRate = sum[0].CallOutAcceptCount > 0 ? Math.round((sum[0].approveSurveyCount / sum[0].CallOutAcceptCount) * 100) : 0
        } else if (data.callType === 'transfer') {
          sum[0].approveSurveyRate = sum[0].NormalTransferAcceptCount > 0 ? Math.round((sum[0].approveSurveyCount / sum[0].NormalTransferAcceptCount) * 100) : 0
        } else if (data.callType === 'dialTransfer') {
          sum[0].approveSurveyRate = sum[0].DialTransferAcceptCount > 0 ? Math.round((sum[0].approveSurveyCount / sum[0].DialTransferAcceptCount) * 100) : 0
        } else {
          let sumCountNum = sum[0].CallOutAcceptCount + sum[0].CallInAcceptCount + sum[0].NormalTransferAcceptCount + sum[0].DialTransferAcceptCount
          if (sumCountNum > 0 && sum[0].approveSurveyCount > 0) {
            sum[0].approveSurveyRate = sumCountNum > 0 ? Math.round((sum[0].approveSurveyCount / sumCountNum) * 100) : 0
          }
        }
        sum[0].approveSurveyRate += '%'
        // 处理table合计的特殊字段
        for (var y in sum[0]) {
          if (y.substr(0, y.length - 1) === 'approveSurvey') {
            if (isExport) {
              sum[0].agent_exten = ''
              if (sum[0].approveSurveyCount === 0) {
                sum[0][y + '_rate'] = Math.round(sum[0][y] / 1 * 100) + '%'
              } else {
                sum[0][y + '_rate'] = sum[0].approveSurveyCount ? Math.round(sum[0][y] / sum[0].approveSurveyCount * 100) + '%' : '0%'
              }
            } else {
              if (sum[0].approveSurveyCount === 0) {
                sum[0][y] = sum[0][y] + '(' + Math.round(sum[0][y] / 1 * 100) + '%' + ')'
              } else {
                sum[0][y] = sum[0].approveSurveyCount ? sum[0][y] + '(' + Math.round(sum[0][y] / sum[0].approveSurveyCount * 100) + '%' + ')' : sum[0][y] + '(0%)'
              }
            }
          }
        }
        return mixData(sum, this.formulas)
      },
      // 关闭配置表头弹窗
      close () {
        this.isShow = false
      },
      // 导出pdf
      confirm () {
        this.dialogVisible = false
        if (this.isShowDetail) {
          exportReportPdf({title: this.$t('report.callReportApproveSurvey') + searchTime(this.query), id: 'name'})
        } else {
          exportReportPdf({title: this.$t('report.callReportApproveSurvey') + searchTime(this.query), id: this.id})
        }
      },
      // 导出详情为自定义进行得判断
      thanThirty (query) {
        let normalStartTime = query.normalStartTime
        let normalEndTime = query.normalEndTime
        let endTIme = normalEndTime.getTime()
        let startTime = normalStartTime.getTime()
        let diff = (endTIme - startTime) / (1000 * 60 * 60 * 24)
        // 大于三十天更改自定义得开始时间
        if (diff > 31) {
          let time = new Date(endTIme - 1000 * 60 * 60 * 24 * 31)
          let newStartTime = getDateTime(time, 'date')
          let lastTime = query.EndTime.split(' ')[1]
          query.StartTime = `${newStartTime} ${lastTime}`
        }
      },
      // 导出表格数据执行的方法(后端)
      exportExcel (isDetail) {
        let myQuery = deepClone(this.query)
        if (myQuery.timeType === 'other_half_hour') {
          let message = checkTime(myQuery.StartTime, myQuery.EndTime, false, false) // 校验类型与时间
          if (message !== true) {
            this.$message.error(this.$t(message))
            return
          }
        }
        // 是否为自定义时间导出并且点击详细导出
        if (myQuery.timeType === 'other_half_hour' && isDetail === true && this.dateType !== 'week') {
          this.thanThirty(myQuery)
        }
        // 初始化查询条件
        let callType = this.value
        myQuery.callType = callType
        myQuery.TimeType = myQuery.timeType
        delete myQuery.timeType
        myQuery.selectedAgentList = myQuery.selectedAgentList.join(',')
        myQuery.accountId = this.$store.state.session.user.account
        myQuery.userType = this.$store.state.session.user.type
        myQuery.user = this.$store.state.session.user._id
        myQuery.type = 'ReportApproveSurveyExport'
        myQuery.reportType = 'call_report_approve_survey'
        myQuery.AgentID = ''
        if (myQuery.TimeType === 'other_half_hour') {
          delete myQuery.yearReport
          delete myQuery.monthReport
          delete myQuery.dayReport
        }
        if (myQuery.TimeType === 'year') {
          delete myQuery.monthReport
          delete myQuery.dayReport
        }
        // 判断是否选择技能组等 但下面无座席故传'000000'无座席
        if ((this.currentQueue.length !== 0 || this.currentdept.length !== 0) && this.selectedAgentListClone.length === 0) {
          myQuery.selectedAgentList = '000000'
        } else if (this.selectedAgentListClone.length !== 0) {
          myQuery.selectedAgentList = this.selectedAgentListClone.join(',')
        }
        myQuery.detailed = false
        if (isDetail === 'detail') {
          myQuery.detailed = true
        }
        let data = {
          Method: 'exportApproveSurveyReport',
          Query: myQuery
        }
        // 导出详细excel更改method
        if (isDetail === true) {
          data.Method = 'exportApproveSurveyReportDetail'
        }
        this.$store.dispatch('exportCallApproveSurveyReport', data).then(() => {
        })
      },
      // 导出PDF
      exportPdf () {
        this.dialogVisible = true
      }
    },
    computed: {
      // 判断是否为过滤座席 返回座席下拉数据
      selectAgents () {
        if (this.$store.getters.userHidden === 'yes') {
          return this.$store.getters.filterStopAgents && this.$store.getters.filterStopAgents.map(agent => ({ label: `${agent.displayName}[${agent.exten}]`, value: agent._id, deptId: agent.deptId ? agent.deptId : '' }))
        }
        return  this.agents
      },
      // 是否展示导出详细excel
      isShowDetailExport () {
        let type = ['week', 'month', 'other_half_hour']
        return type.includes(this.dateType)
      },
      indexStart () {
        let isBool = Boolean(this.isInviteStatistics)
        return isBool ? 11 : 9
      },
      // 自定义表头
      formulasConfig () {
        return this.formulas.map((d, i) => {
          return {
            displayname: d.displayname,
            name: d.name,
            order: d.order,
            show: d.show,
            timeType: 'none',
            digits: d.digits,
            type: d.type
          }
        })
      }
    },
    watch: {
      // 监测自定义公式变化 更新数据
      formulas (cur, old) {
        if (this.isSearch) {
          return
        }
        if (!this.serveNumData || this.serveNumData.length === 0) {
          return
        }
        var data = this.getSearchQueryData()
        this.serveNumData = mixData(deepClone(this.serveNumData), this.formulas)
        this.sum = this.dealSum(this.baseData, data, this.headOptions)
      },
      // 选择后是否显示当前下座席
      isShowAgent (cur) {
        if (cur) {
          this.query.selectedAgentList = this.selectedAgentListClone
        } else {
          this.query.selectedAgentList = []
        }
      }
    },
    components: {
      affix,
      unfold,
      dateTime,
      reportTable,
      sueveyDetail,
      FormulaEditorDialog
    },
    beforeMount () {
      let currentPbx = this.$store.state.session.user.pbx
      console.log(this.$store.state.session.account, 9999)
      if (isHasFunc('func_forbid_config_formula', this.$store.state.session.user)) {
        this.configFormula = false // 没有自定义公式的配置权限
      }
      this.$store.dispatch('getNewFeaturesReport', {pbx: currentPbx}).then((res) => {
        if (!res.success) {
          this.search()
          return
        }
        this.search()
        if (res.data.features && res.data.features.indexOf('InviteStatistics') > -1) {
          this.isInviteStatistics = true
        }
      }).catch((err) => {
        console.log(err)
        this.search()
      })
      this.$store.dispatch('getCache', {type: 'queues'}).then((peer) => {
        this.queues = peer
      })
      this.$store.dispatch('getCache', {type: 'depts'}).then((dept) => {
        this.depts = dept.filter(item => {
          return item.pId
        })
        this.depts.push({
          name: '未分配部门',
          treePath: 'noDept'
        })
      })
      this.$store.dispatch('getCache', { type: 'agents' }).then(agents => {
        this.agents = agents.map(agent => ({ label: `${agent.displayName}[${agent.exten}]`, value: agent._id, deptId: agent.deptId ? agent.deptId : '' }))
      })
    }
  }
</script>
<style lang="stylus" scoped>
  @import "../../../../assets/common.styl"
  .survey
    .agent_search
      .wrap_conti
        margin 14px 0 0 20px
        .ski
          margin-right 26px
        .chan_ag
          float left
          margin-right 20px
        .el-radio
          margin-right 30px
        .dept
          .el-radio
            margin-right 42px
    .tip
      cursor pointer
      display inline-block
      height 16px
      width 16px
      border 1px solid $c-main
      text-align center
      line-height 15px
      border-radius 50%
      margin 0px 0 0 6px
      .iconfont
        border none
        font-size 10px
        color $c-main
    .skill
      .el-select
        width 400px
        margin-right 16px
      .ski
        display inline-block
        width 80px
</style>
